<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2018/6/13
 * Time: 10:40
 */
namespace app\api\controller;
use think\Controller;
use think\Db;
use Qiniu\Auth;
class  Base extends Controller {
    protected $_error;
    protected $_header;//用户的请求头信息
    protected $otherLogin  = '您的账号已在其他设备登录';
    protected $frost = '您的账号已被冻结';
    protected $del = '您的账号已注销';
    // 构造函数 数据类型最大到6了
    public function _initialize(){
        // 如果配置项为空 则直接返回

    }

    /**
     * 验证唯一——单点登录
     * user_id，time，salt，value
     * @return string
     */
    public  function checkAll($uid,$time,$value,$reqKey){
        if($uid == 0) {
            return 111;
        } else {
            $user = Db::table('up_u_user')->where('user_id',$uid)->find();
            if($user['user_status'] == 2){ // 冻结
                return 110;
            }
            if($user['user_status'] == 3){ // 删除
                return 1103;
            }
            $token = $user['user_token'];
            $appId = "F20201279836621";
            $appkey = "9FM807G0-MF12-J521-6998-6D57N0GHN8BV";
            $myreqKey = md5($appId . 'XW' . $appkey . 'XW' . $time);
            $myvalue = md5($uid . 'XW' . $token . 'XW' . $time);
            if($myvalue != $value || $myreqKey != $reqKey) {
                return 112;
            } else {
                return 111;
            }
        }
    }

    /**
     * 获取uuid
     * @param string $prefix
     * @return string
     */
    public function uuid($prefix = '')
    {
        $chars = md5(uniqid(mt_rand(), true));
        $uuid  = substr($chars,0,8);
        $uuid .= substr($chars,8,4);
        $uuid .= substr($chars,12,4);
        $uuid .= substr($chars,16,4);
        $uuid .= substr($chars,20,12);
        return $prefix . $uuid;
    }
    /**
     * 获取七牛token
     * @return string
     */
    public function getQiniuToken(){
        require_once ('../extend/qiniu/autoload.php');
        header("Access-Control-Allow-Origin:*");
        $accessKey = config('qiniu')['accessKey'];
        $secretKey = config('qiniu')['secretKey'];
        $bucket = config('qiniu')['bucket'];
//        $auth = new Qiniu();
        $auth = new Auth($accessKey, $secretKey);
        $token = $auth->uploadToken($bucket);
        return json_encode(array('data'=>$token));
    }


    /**
     * formatTime 时间格式化
     * @param $time 时间戳
     * @return string
     */
    public function formatTime($time) {
        $now_time = time();
        $t = $now_time - $time;
        $yea = (int) ($t / (86400 * 30 * 12));
        if ($yea >= 1) {
            return $yea.'年前';
        }
        $mon = (int) ($t / (86400 * 30));
        if ($mon >= 1) {
            return '一个月前';
        }
        $day = (int) ($t / 86400);
        if ($day >= 1) {
            return $day . '天前';
        }
        $h = (int) ($t / 3600);
        if ($h >= 1) {
            return $h . '小时前';
        }
        $min = (int)($t / 60);
        if ($min >= 1) {
            return $min . '分钟前';
        }
        return '刚刚';
    }

    /**
     * 获取任意长度的随机字符串
     * @param $length
     * @return string
     */
//    function getRandChar($length)
//    {
//        $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
//            'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
//            't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
//            'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
//            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
//            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
//        $char_txt = '';
//        for ($i = 0; $i < $length; $i++) {
//            $char_txt .= $chars[array_rand($chars)];
//        }
//        return $char_txt;
//    }

    /**
     * 验证码
     * @param $length
     * @return string
     */
    function getCodeChar($length)
    {
        $chars = array(
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        $char_txt = '';
        for ($i = 0; $i < $length; $i++) {
            $char_txt .= $chars[array_rand($chars)];
        }
        return $char_txt;
    }
    public function getAcount()
    {
        //==========base里放到===============
        $zimu = range('a','z');
        $one = rand(0,25);
        $two = rand(0,25);
        $thr = rand(0,25);
        $four = rand(0,25);
        $zimu2 = $zimu[$one].$zimu[$two].$zimu[$thr].$zimu[$four];
        $num = rand(100000,999999);
        return $zimu2.$num;
        //=========================
    }

    //------------------------mww-------------------------------------------------------

    /**
     * 极光推送
     * @param $type 1:推送个人  2:推送全体
     * @param $alias 别名 user_id OR token
     * @param $message 推送消息内容
     * @param $extras 扩展字段接受数组
     * @return array
     */
    public function Jpush($type,$alias,$message,$extras)
    {
        if(is_string($alias) || is_int($alias)){
            $alias = (string)$alias;
        }
        import('jpush.autoload', EXTEND_PATH);
        //初始化JPushClient
        $client = new \JPush\Client(config('jpush.appKey'),config('jpush.masterSecret'));
        //生成推送Payload构建器
        $push = $client->push();
        //推送平台 'all'  OR  ['ios','android']  OR  'ios','android'
        $push->setPlatform('all');
        //1:推送个人  2:推送全体
        if($type==1){
            $push->addAlias($alias);//按别名推送
        }else{
            $push->addAllAudience();//广播消息推送
        }
        //IOS推送
        $push->iosNotification($message, [
                'alert'=>$message,
                'badge' => '+1',
                'extras' => $extras,
                'sound'=>'default'
            ]
        );
        //Android推送
        $push->androidNotification($message, [
                'alert'=>$message,
                'extras' => $extras
            ]
        );
        $push->message($message, [
//            'title' => 'Hello',
            'content_type' => 'text',
            'extras' => $extras
        ]);
        return $push->send();
    }

    /**
     * 获取用户数据
     * @param $user_id
     * @param string $field
     * @param int $type
     * @return array|false|mixed|\PDOStatement|string|\think\Model
     */
    public function getUserInfo($user_id,$field='',$type=1)
    {
        if($field){
            if($type == 1){
                $res = Db::table('up_u_user')->where('user_id',$user_id)->value($field);
            }else{
                $res = Db::table('up_u_user')->where('user_id',$user_id)->field($field)->find();
            }
        }else{
            $res = Db::table('up_u_user')->where('user_id',$user_id)->find();
        }
        return $res;

    }

    /**
     * 获取某表的条件数据
     * @param $table
     * @param $where
     * @param string $field
     * @param int $type
     * @return array|false|mixed|\PDOStatement|string|\think\Model
     */
    public function getTableData($table,$where,$field='',$type=1)
    {
        if($field){
            if($type == 1){
                $res = Db::table($table)->where($where)->value($field);
            }else{
                $res = Db::table($table)->where($where)->field($field)->find();
            }
        }else{
            $res = Db::table($table)->where($where)->find();
        }
        return $res;

    }

    /**
     * foreach循环给字符串转数组
     * @return bool
     */
    public function foreachStrArr($data,$field,$type='',$typevalue='',$like='',$user_id='')
    {
        foreach ($data as $k => $v){
            //把图片切割成数组
            if($type){
                if($v[$type] == $typevalue){
                    if($v[$field]){
                        $data[$k][$field] = explode(',',$v[$field]);
                    }else{
                        $data[$k][$field] = [];
                    }
                }
            }else{
                if($v[$field]){
                    $data[$k][$field] = explode(',',$v[$field]);
                }else{
                    $data[$k][$field] = [];
                }
            }
            //like是1代表要看下是不是喜欢这个帖子
            if($like == 1){
                $zan = $this->getTableData('up_zan',['zan_type' => 3,'zan_new_com_id' => $v['t_id'],'zan_user_id' => $user_id]);
                $data[$k]['like'] = 1; //我没有赞
                if($zan){
                    $data[$k]['like'] = 2;
                }
            }
        }
        return $data;
    }
    /**
     * 赛事数据
     */
    public function matchDatas($where,$order,$page,$rows,$field)
    {
        $datas = Db::table('up_match_fj mf')
            ->join('up_match_live mv', 'mf.mf_fid=mv.mv_fid and mf.mf_name=mv.mv_name and mf.mf_match_time=mv.mv_match_time and (mf.mf_home_name_cn=mv.mv_home_name_cn or mf.mf_home_name_en=mv.mv_home_name_en)', 'left')
            ->where($where)
            ->order($order)
            ->page($page,$rows)
            ->field($field)
            ->select();
        return $datas;
    }
    /**
     * 只为专家数据和赛事数据
     */
    public function dataLikes($users,$user_id,$type=1)
    {
        if($type == 1){
            foreach ($users as $k => $v){
                if($v['user_tags']){
                    $users[$k]['user_tags'] = explode(',',$v['user_tags']);
                }else{
                    $users[$k]['user_tags'] = [];
                }
                //有没有关注
                $users[$k]['like'] = 1;
                $have = $this->getTableData('up_like',['like_user_id' => $user_id,'like_other_user' => $v['user_id']]);
                if($have){
                    $users[$k]['like'] = 2;
                }
            }
        }else{
            foreach ($users as $k => $v){
                //有没有关注
                $users[$k]['like'] = 1;
                $have = $this->getTableData('up_match_love',['love_user_id' => $user_id,'love_fj_matchid' => $v['mf_fj_matchid']]);
                if($have){
                    $users[$k]['like'] = 2;
                }
                //联赛logo
                $users[$k]['league_logo'] = Db::table('up_sport_team')
                    ->where('st_fid',$v['mf_fid'])
                    ->where('st_league_id',$v['mf_league_id'])
                    ->value('st_logo');
            }
        }
        return $users;
    }
    public function dataSingleMatch($v){
        $decodeData = json_decode($v['mf_json'],true);
        $match[$k]['mf_home_score'] = $decodeData['homeScore'];
        $match[$k]['mf_away_score'] = $decodeData['awayScore'];
        if($fid == 1){
            $match[$k]['startTimeAfter'] = round((time() - strtotime($decodeData['startTime']))/60);
            $match[$k]['homeHalfScore'] = $decodeData['homeHalfScore'];
            $match[$k]['awayHalfScore'] = $decodeData['awayHalfScore'];
            $match[$k]['homeCorner'] = $decodeData['homeCorner'];
            $match[$k]['awayCorner'] = $decodeData['awayCorner'];
        }else{
            $match[$k]['remainTime'] = $decodeData['remainTime'];
            $match[$k]['home1'] = $decodeData['home1'];
            $match[$k]['home2'] = $decodeData['home2'];
            $match[$k]['home3'] = $decodeData['home3'];
            $match[$k]['home4'] = $decodeData['home4'];
            $match[$k]['away1'] = $decodeData['away1'];
            $match[$k]['away2'] = $decodeData['away2'];
            $match[$k]['away3'] = $decodeData['away3'];
            $match[$k]['away4'] = $decodeData['away4'];
        }
        return -1;
    }
    public function getLetter($num){
        $limit = array( //gb2312 拼音排序
            array(45217,45252), //A
            array(45253,45760), //B
            array(45761,46317), //C
            array(46318,46825), //D
            array(46826,47009), //E
            array(47010,47296), //F
            array(47297,47613), //G
            array(47614,48118), //H
            array(0,0),     //I
            array(48119,49061), //J
            array(49062,49323), //K
            array(49324,49895), //L
            array(49896,50370), //M
            array(50371,50613), //N
            array(50614,50621), //O
            array(50622,50905), //P
            array(50906,51386), //Q
            array(51387,51445), //R
            array(51446,52217), //S
            array(52218,52697), //T
            array(0,0),     //U
            array(0,0),     //V
            array(52698,52979), //W
            array(52980,53688), //X
            array(53689,54480), //Y
            array(54481,55289), //Z
        );
        $char_index=65;
        foreach($limit as $k=>$v){
            if($num>=$v[0] && $num<=$v[1]){
                $char_index+=$k;
                return $char_index;
            }
        }
        return -1;
    }
}